package csu.webcourse.mypetstore.web.servlet;

import csu.webcourse.mypetstore.domain.Account;
import csu.webcourse.mypetstore.domain.Cart;
import csu.webcourse.mypetstore.domain.CartItem;
import csu.webcourse.mypetstore.domain.Item;
import csu.webcourse.mypetstore.service.CartService;
import csu.webcourse.mypetstore.service.CategoryService;
import csu.webcourse.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

public class AddItemToCartServlet extends HttpServlet {
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    private CategoryService categoryService;
    private CartService cartService;
    private int flag=0;
    private static ArrayList<String>ItemIds =new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        cartService = new CartService();


        String workingItemId = req.getParameter("workingItemId");
        String userId=req.getParameter("userId");

        //用户为登录时，将添加购物车的ItemId数据用Arraylist保存起来
        if(userId==null||userId.equals("")){
            ItemIds.add(workingItemId);
            CartFormServlet.setItemIds(ItemIds);
        }


        //若用户已登录，将未登录时添加的购物车项加入数据库
        if(userId!=null&&!userId.equals("")) {
            if(ItemIds.size()>0){
                for (int i=0;i<ItemIds.size();i++){
                    cartService.insertCartList(ItemIds.get(i), userId);
                }
                ItemIds.clear();
                CartFormServlet.setItemIds(ItemIds);
            }

            HttpSession session=req.getSession();
            if(flag==0){
                session.removeAttribute("cart");
                flag=1;
            }
            //将未登录时保存在购物车中的数据插入登录用户的数据库
           if(ItemIds.size()>0){
               for(int i=0;i<ItemIds.size();i++){
                   String itemId=ItemIds.get(i);
                   cartService.insertCartList(itemId, userId);
               }
               //清空临时数据
               ItemIds.clear();
           }

            cartService.insertCartList(workingItemId, userId);
        }

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null) {
            cart = new Cart();
        }
        if(cartService.containsItemId(cart, workingItemId)) {
            cartService.incrementQuantityByItemId(cart, workingItemId);
        }else {
            categoryService = new CategoryService();
            boolean isInStock = categoryService.isItemInStock(workingItemId);
            Item item = categoryService.getItem(workingItemId);
            cartService.addItem(cart, item, isInStock);
        }

        session.setAttribute("cart", cart);
        if(!userId.equals("")) {
            Account account = (Account) session.getAttribute("loginAccount");
            if (account != null) {
                HttpServletRequest httpRequest = req;
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();
                //最后加入的信息“XXXXX”应当为该界面的信息以及一些商品信息
                String logInfo = logService.logInfo(" ") + strBackUrl + account.getUsername() + "添加" + workingItemId +"到购物车";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }

            resp.sendRedirect("cartForm?userId=" + userId);
        }
        else {
            Account account = (Account) session.getAttribute("loginAccount");
            if (account != null) {
                HttpServletRequest httpRequest = req;
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();
                //最后加入的信息“XXXXX”应当为该界面的信息以及一些商品信息
                String logInfo = logService.logInfo(" ") + strBackUrl + "用户添加" + workingItemId +"到购物车";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }
            resp.sendRedirect("cartForm");
        }
//        req.getRequestDispatcher(CART_FORM).forward(req, resp);
    }
    public static void setItemIds(ArrayList<String> itemIds){
        ItemIds=itemIds;
    }
}
